package com.carleasoft.mps.security.permission.data;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.bytecode.SignatureAttribute;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;


/**
 * 引用此功能的服务模块需要注入 @EnableCarleaRedis
 *
 * @author ztm
 * @date 2021-09
 * @project
 */
@Slf4j
@Aspect
@Component
public class DataPermissionScopeAspect {

    public DataPermissionScopeAspect() {
    }

    @Pointcut("@annotation(com.carleasoft.mps.security.permission.data.RequiresDataPermission)")
    public void dataPermissionPointCut() {
    }

    @Before("dataPermissionPointCut()")
    public void doBefore(JoinPoint point) throws Throwable {
        log.info("--------------------dataPermission begin------------------->>>>>>>");
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            RequiresDataPermission controllerDataScope = (RequiresDataPermission) method.getAnnotation(RequiresDataPermission.class);
            RequiresDataPermission.Scope[] scopes = controllerDataScope.dataPerm();
            Arrays.stream(scopes).forEach(scope -> {
                ThreadSessionContext.setDataPermissionMethods(scope);
            });
        }
    }

    @After("dataPermissionPointCut()")
    public void doAfter(JoinPoint point) throws Throwable{
        ThreadSessionContext.close();
        log.info("<<<<<<<<<--------------------dataPermission end-------------------");
    }


}
